package com.amoby.main.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.amoby.main.entity.AlipayOrder;
import com.amoby.main.entity.Business;
import com.amoby.main.entity.Cbabill;
import com.amoby.main.mapper.AlipayOrderMapper;
import com.amoby.main.service.AlipayOrderTransferService;
import com.amoby.main.service.CbaBillService;

@Service
public class AlipayOrderTransferServiceImpl implements AlipayOrderTransferService {
    private static Log        logger = LogFactory.getLog(AlipayOrderTransferServiceImpl.class);
    @Autowired
    private AlipayOrderMapper alipayOrderMapper;
    @Autowired
    private CbaBillService    cbaBillService;
    
    @Override
    public int alipayOrderTransfer(Map<String, Object> map) {
        logger.debug("支付宝活动订单对应商家转账任务开始");
        List<Business> list = alipayOrderMapper.needTransferAlipayBus(map);
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        /** 2每个商家执行转账 */
        int count = 0;
        if(list.size()>0){
            for (Business b : list) {
                try {
                    map.put("bsId", b.getId());
                    List<AlipayOrder> orders = alipayOrderMapper.needTransferAlipayOrder(map);
                    if (!orders.isEmpty()) {
                        Cbabill bill = cbaBillService.startAlipayOrderBill(orders, b);
                        if (bill != null && bill.getId() != null) {
                            logger.debug("支付宝订单处理成功=" + bill.getId() + "=========" + b.getId());
                            count++;
                        }
                    }
                } catch (Exception e) {
                    logger.error("支付宝活动订单对应商家ID:" + b.getId() + "转账失败", e);
                }
            }
        }
        logger.debug("支付宝活动订单对应商家1点转账任务结束");
        return count;
    }

    /**
     * 每月8号转账
     */
    @Override
    public int alipay8Transfer() {
        logger.debug("支付宝活动订单对应商家转账任务开始");
        List<Business> list = alipayOrderMapper.alipayTransfer();
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        Map<String, Object> map = new HashMap<String, Object>();
        /** 2每个商家执行转账 */
        int count = 0;
        if(list.size()>0){
            for (Business b : list) {   
                try {
                    map.put("bsId", b.getId());
                    List<AlipayOrder> orders = alipayOrderMapper.transferAlipayOrderAll(map);
                    if (!orders.isEmpty()) {
                        Cbabill bill = cbaBillService.startAlipayOrderAll(orders, b);
                        if (bill != null && bill.getId() != null) {
                            logger.debug("支付宝订单处理成功=" + bill.getId() + "=========" + b.getId());
                            count++;
                        }
                    }
                } catch (Exception e) {
                    logger.error("支付宝活动订单对应商家ID:" + b.getId() + "转账失败", e);
                }
            }
        }
        logger.debug("支付宝活动订单对应商家1点转账任务结束");
        return count;
    }
    /**
     * 支付宝活动订单转账
     */
    @Override
    public int alipayTransfer() {
        logger.debug("支付宝活动订单查询未转账的对应商家");
        List<Business> list = alipayOrderMapper.alipayTransfer();
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        if(list.size()>0){
            for (Business b : list) {
                try {
                    map.put("bsId", b.getId());
                    List<AlipayOrder> orders = alipayOrderMapper.transferAlipayOrderAll(map);
                    Double amount = 0d; // 总转账金额
                    if (!orders.isEmpty()) {
                        for (AlipayOrder o : orders) {    //计算转账总金额
                            amount += new BigDecimal(o.getAmount().toString()).subtract(new BigDecimal(o.getBrokerage().toString()))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                        BigDecimal transferPoolLmt = cbaBillService.transferPoolLmt();
                        logger.debug("转账池设置限额======="+transferPoolLmt+"==========="+amount);
                        // 判断转账池金额和未转账金额  如果转账金额>=限额则转账  
                        if((transferPoolLmt.compareTo(new BigDecimal(amount.toString())) < 0) || (Double.valueOf(transferPoolLmt.toString()).equals(amount))){
                            logger.debug("需要转账的订单======" + orders.size() + "=========" + orders);
                            Cbabill bill = cbaBillService.startAlipayTransfer(orders, b, amount);
                            if (bill != null && bill.getId() != null) {
                                logger.debug("支付宝订单处理成功=" + bill.getId() + "=========" + b.getId());
                                count++;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("支付宝活动订单对应商家ID:" + b.getId() + "转账失败", e);
                }
            }
        }
        logger.debug("支付宝活动订单对应商家0点转账任务结束");
        return count;
    }
    
    /**
     * 批量转账
     */
    @Override
    public int alipayTransferBatch() {
        logger.debug("支付宝活动订单查询未转账且可以转账的对应商家");
        List<Business> list = alipayOrderMapper.alipayTransferBus();
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        Double amount = 0d; // 总转账金额
        try {
            if(list.size()>0){
    			for (Business b : list) {
    			    map.put("bsId", b.getId());
    			    List<AlipayOrder> orders = alipayOrderMapper.transferAlipayOrderAll(map);
    			    if (!orders.isEmpty()) {
    			        for (AlipayOrder o : orders) {    //计算转账总金额
    			            amount += new BigDecimal(o.getAmount().toString()).subtract(new BigDecimal(o.getBrokerage().toString()))
    			                    .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    			        }
    			    }
    			    count++;
    			}
    			logger.debug("批量转账的总金额为：====================================="+amount);
    			BigDecimal transferPoolLmt = cbaBillService.transferPoolLmt();
    			// 判断转账池金额和未转账金额  如果转账金额>=限额则转账  
    			if((transferPoolLmt.compareTo(new BigDecimal(amount.toString())) < 0) || (Double.valueOf(transferPoolLmt.toString()).equals(amount))){
    			    cbaBillService.startAlipayTransferBatch(list);
    			}
			}
		} catch (Exception e) {
			logger.error("支付宝活动订单转账失败", e);
		}
        return count;
    }
    
    
    /**
     * 渠道批量转账
     */
    @Override
    public int alipayTransferChannelBatch() {
        logger.debug("支付宝活动订单查询批量未转账且可以转账的对应商家");
        List<Business> list = alipayOrderMapper.alipayTransferChannel();
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        Double amount = 0d; // 总转账金额
        try {
            if(list.size()>0){
                for (Business b : list) {
                    map.put("bsId", b.getId());
                    List<AlipayOrder> orders = alipayOrderMapper.transferAlipayOrderAll(map);
                    if (!orders.isEmpty()) {
                        for (AlipayOrder o : orders) {    //计算转账总金额
                            amount += new BigDecimal(o.getAmount().toString()).subtract(new BigDecimal(o.getBrokerage().toString()))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                    }
                    count++;
                }
                logger.debug("批量转账的总金额为：====================================="+amount);
                BigDecimal transferPoolLmt = cbaBillService.transferPoolLmt();
                // 判断转账池金额和未转账金额  如果转账金额>=限额则转账  
                if((transferPoolLmt.compareTo(new BigDecimal(amount.toString())) < 0) || (Double.valueOf(transferPoolLmt.toString()).equals(amount))){
                    cbaBillService.startAlipayTransferBatch(list);
                }
            }
        } catch (Exception e) {
            logger.error("支付宝活动订单转账失败", e);
        }
        return count;
    }
    
    /**
     * 批量转账（每月8号）
     */
    @Override
    public int alipay8TransferBatch() {
        logger.debug("支付宝活动订单查询未转账且可以转账的对应商家");
        List<Business> list = alipayOrderMapper.alipayTransferBus();
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        Double amount = 0d; // 总转账金额
        try {
            if(list.size()>0){
    			for (Business b : list) {
    			    map.put("bsId", b.getId());
    			    List<AlipayOrder> orders = alipayOrderMapper.transferAlipayOrderAll(map);
    			    if (!orders.isEmpty()) {
    			        for (AlipayOrder o : orders) {    //计算转账总金额
    			            amount += new BigDecimal(o.getAmount().toString()).subtract(new BigDecimal(o.getBrokerage().toString()))
    			                    .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    			        }
    			    }
    			    count++;
    			}
    			// 每月8号的不受限制
    			cbaBillService.startAlipayTransferBatch(list);
            }
		} catch (Exception e) {
			logger.error("支付宝活动订单转账失败", e);
		}
        return count;
    }

    /**
     * 渠道批量转账（每月8号）
     */
    @Override
    public int alipay8TransferChannelBatch() {
        logger.debug("支付宝活动订单查询批量未转账且可以转账的对应商家");
        List<Business> list = alipayOrderMapper.alipayTransferChannel();
        logger.debug("支付宝活动订单需要转账的商家信息=" + list);
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        Double amount = 0d; // 总转账金额
        try {
            if(list.size()>0){
                for (Business b : list) {
                    map.put("bsId", b.getId());
                    List<AlipayOrder> orders = alipayOrderMapper.transferAlipayOrderAll(map);
                    if (!orders.isEmpty()) {
                        for (AlipayOrder o : orders) {    //计算转账总金额
                            amount += new BigDecimal(o.getAmount().toString()).subtract(new BigDecimal(o.getBrokerage().toString()))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                    }
                    count++;
                }
                // 每月8号的不受限制
                cbaBillService.startAlipayTransferBatch(list);
            }
        } catch (Exception e) {
            logger.error("支付宝活动订单转账失败", e);
        }
        return count;
    }
}
